package com.example.messagedemo.controller;


import com.example.messagedemo.common.WebsocketConst;
import com.example.messagedemo.model.dto.MessageReq;
import com.example.messagedemo.model.vo.Result;
import com.example.messagedemo.websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * 测试插座控制器
 *
 * @author dlp
 * @date 2024/08/22
 */
@RestController
@RequestMapping("/sys/socketTest")
public class TestSocketController {

    @Autowired
    private WebSocket webSocket;

    @PostMapping("/sendAll")
    public Result<String> sendAll(@RequestBody MessageReq jsonObject) {
        Result<String> result = new Result<String>();
        String message = jsonObject.getMessage();
        JSONObject obj = new JSONObject();
        //全部订阅消息
        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_TOPIC);
        obj.put(WebsocketConst.MSG_ID, "M0001");
        obj.put(WebsocketConst.MSG_TXT, message);
        webSocket.sendMessage(obj.toJSONString());
        result.setResult("群发！");
        return result;
    }

    @PostMapping("/sendUser")
    public Result<String> sendUser(@RequestBody MessageReq jsonObject) {
        Result<String> result = new Result<String>();
        List<String> userId = jsonObject.getUserId();
        String message = jsonObject.getMessage();
        JSONObject obj = new JSONObject();
        //用户消息
        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
        if (userId.size()==1) {
            obj.put(WebsocketConst.MSG_USER_ID, userId.get(0));
        }
        //发送人id
        obj.put(WebsocketConst.MSG_ID, "M0001");
        obj.put(WebsocketConst.MSG_TXT, message);
        webSocket.sendMessage(userId.toArray(new String[0]), obj.toJSONString());
        result.setResult("多个指定单发");
        return result;
    }

    @GetMapping("/obtainOnlinePersonnel")
    public Result<List<String>> getOnlineUsersIds(){
        return Result.OK(webSocket.getOnlineUsersIds());
    }



    //客户端连接socket需要开启服务的心跳检测，每5秒发生一个心跳包检测
}